import os

from PySide6.QtCore import QFile, Qt, QAbstractTableModel
from PySide6.QtGui import QPixmap, QPalette
from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QApplication, QMainWindow, QLineEdit, QMessageBox, QStatusBar, QLabel, QProgressBar, \
  QWidget
from loguru import logger
from conf import Config as myconf


class MainUI(QMainWindow):
  def __init__(self):
    super(MainUI, self).__init__()
    self.login_win = self.load_login_ui()
    self.biz = Biz(self)  # send_log_signal=send_log_signal

  def load_login_ui(self):
    os.chdir(os.path.dirname(__file__))
    quick_loader = QUiLoader()  # 如果pyside6版本过高，可能会卡死在这里  --> 后来发现，在靠前的位置加一句 QUiLoader() ，它就可以了。
    ui_file = QFile("ui/login.ui")
    ui_file.open(QFile.ReadOnly)
    login_win = quick_loader.load(ui_file)
    self.login_win_setting(login_win)

    # # 设置事件过滤器
    # close_filter = CloseFilter(self)
    # self.installEventFilter(close_filter)
    ui_file.close()
    return login_win

  def login_win_setting(self, login_win):
    login_win.edt_user.setPlaceholderText("请输入登录ID")
    login_win.edt_pwd.setPlaceholderText("请输入密码")  # 设置占位符文本
    login_win.edt_pwd.setEchoMode(QLineEdit.Password)  # 设置回显模式为

    login_win.btn_login.clicked.connect(self.btnLoginClick)
    login_win.btn_cancel.clicked.connect(self.btnCancelClick)

    self.set_login_win_background(login_win)
    self.tmp_load_user_password(login_win)

  def tmp_load_user_password(self,login_win):
    if hasattr(myconf, 'test_user') and hasattr(myconf, 'test_password'):
      login_win.edt_user.setText(myconf.test_user)
      login_win.edt_pwd.setText(myconf.test_password)


  def set_login_win_background(self, login_win):
    pixmap = QPixmap(r"ui/login_back.jpg")

    # 创建一个QPalette对象
    palette = QPalette()

    # 将图片设置为背景
    palette.setBrush(self.backgroundRole(), pixmap)
    login_win.setPalette(palette)

  def btnLoginClick(self):
    # 获取用户名和密码
    username = self.login_win.edt_user.text()
    password = self.login_win.edt_pwd.text()
    # 判断 username 和 password 是否为空
    if not username or not password:
      QMessageBox.warning(self, "注意", "用户名或密码不能为空！")
      return
    # 调用业务逻辑类 Biz 进行登录
    if not self.biz.login(username, password):
      QMessageBox.warning(self, "注意", "登录失败！")
      return

    self.start_main_win()

  def btnCancelClick(self):
    logger.info("取消")
    app.quit()

  def start_main_win(self):
    logger.info("打开主窗口")
    if hasattr(self, 'login_win') and self.login_win:
      self.login_win.close()
    quick_loader = QUiLoader()
    ui_file = QFile("ui/main.ui")
    ui_file.open(QFile.ReadOnly)
    self.ui = quick_loader.load(ui_file)
    ui_file.close()
    self.init_status_bar()
    self.ui.show()
    self.load_biz_data()

  def load_biz_data(self):
    # 加载业务数据"
    paper_model = self.biz.load_paper_model()
    self.ui.paper_table_view.setModel(paper_model)

  def init_status_bar(self):
    # 创建状态栏
    status_bar = QStatusBar()
    self.ui.setStatusBar(status_bar)

    # 创建一个简单的分割线Widget
    separator = QWidget()  # 创建一个QWidget对象
    separator.setFixedHeight(2)  # 设置分隔线的高度
    separator.setStyleSheet("background-color: black;")  # 设置分隔线的颜色

    # 将分割线添加到状态栏
    # status_bar.addPermanentWidget(separator,1)  # 使用addPermanentWidget以保证不会被临时消息遮挡

    # 创建一个标签显示状态信息
    status_label = QLabel("Ready")
    # 创建一个进度条
    progress_bar = QProgressBar()

    # 将标签和进度条添加到状态栏
    status_bar.addWidget(status_label, 1)  # 第二个参数是stretch factor
    status_bar.addWidget(progress_bar, 2)
    progress_bar.hide()  # 隐藏进度条

class PaperTableModel(QAbstractTableModel):
  def __init__(self, data, parent=None):
    super().__init__(parent)
    self._data = data

  def rowCount(self, parent=None):
    return len(self._data)

  def columnCount(self, parent=None):
    return len(self._data[0]) if self._data else 0

  def data(self, index, role=Qt.DisplayRole):
    if role == Qt.DisplayRole:
      return self._data[index.row()][index.column()]
    return None

  def headerData(self, section, orientation, role):
    if role == Qt.DisplayRole:
      if orientation == Qt.Horizontal:
        return "Column {}".format(section)
      else:
        return "Row {}".format(section)

class Biz:

  def __init__(self, app):
    super().__init__()
    self.app = app

  def login(self, username, password):
    # 假设这里调用了数据库进行登录验证
    if username == "admin" and password == "123456":
      return True
    return False

  def load_paper_model(self):
    # 假设这里调用了数据库进行数据查询
    data = [
      ["标题1", "作者1", "年份1"],
      ["标题2", "作者2", "年份2"]]
    model = PaperTableModel(data)
    return model

if __name__ == '__main__':
  QUiLoader()
  app = QApplication([])
  logger.info("启动程序")
  w = MainUI()
  w.login_win.show()
  app.exec()
